package com.didi.gulimall.order.web;

import com.alibaba.fastjson.JSON;
import com.didi.gulimall.common.constant.OrderConstant;
import com.didi.gulimall.common.entity.LocalMqEntity;
import com.didi.gulimall.common.exception.DuplicateFieldsException;
import com.didi.gulimall.common.to.OrderBackVo;
import com.didi.gulimall.common.utils.LogUtils;
import com.didi.gulimall.common.utils.R;
import com.didi.gulimall.common.vo.OrderItemVo;
import com.didi.gulimall.mq.GuliRabbitTemplate;
import com.didi.gulimall.order.service.OrderWebService;
import com.didi.gulimall.order.vo.OrderConfirmVo;
import com.didi.gulimall.order.vo.OrderSubmitVo;
import com.didi.gulimall.order.vo.PayOrderVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;

/**
 * @author 10626
 */
@Controller
@Slf4j
@Api("订单前端")
public class OrderWebController {
    @Autowired
    private OrderWebService orderWebService;

    @Autowired
    private GuliRabbitTemplate rabbitTemplate;

    @Value("${gulimall.cart}")
    private String cartHtml;

    @Value("${gulimall.order}")
    private String orderHtml;

    @GetMapping("toTrade.html")
    public String toTrade(Model model) throws ExecutionException, InterruptedException {
        try {
            OrderConfirmVo orderConfirmVo = orderWebService.confirmOrder();
            log.info("返回数据：{}", JSON.toJSONString(orderConfirmVo));
            model.addAttribute("trade", orderConfirmVo);
            return "trade";
        } catch (DuplicateFieldsException e) {
            log.error(LogUtils.getStackTraceInfo(e));
            return "redirect:" + cartHtml + "/cartList.html";
        }
    }
    @GetMapping("seckill/toTrade.html")
    public String seckillToTrade(Model model) throws ExecutionException, InterruptedException {
        try {
            OrderConfirmVo orderConfirmVo = orderWebService.seckillConfirmOrder();
            log.info("返回数据：{}", JSON.toJSONString(orderConfirmVo));
            model.addAttribute("trade", orderConfirmVo);
            return "trade";
        } catch (DuplicateFieldsException e) {
            log.error(LogUtils.getStackTraceInfo(e));
            return "redirect:" + cartHtml + "/cartList.html";
        }
    }

    @GetMapping("toPay.html")
    public String payHtml(@RequestParam("totalOrderSn") String totalOrderSn, Model model) {
        PayOrderVo payOrderVo = orderWebService.getOrderVo(totalOrderSn);
        if (payOrderVo != null) {
            model.addAttribute("order", payOrderVo);
            return "pay";
        } else {
            return "redirect:" + orderHtml + "toTrade.html";
        }
    }

    @PostMapping("submitOrder")
    public String toPay(OrderSubmitVo orderSubmitVo, RedirectAttributes redirectAttributes) throws ExecutionException, InterruptedException {
        log.info(orderSubmitVo.toString());
        String orderSn = "";
        try {
            if (orderSubmitVo.getPaymentTypes().equals(OrderConstant.BUY)){
                orderSn= orderWebService.submitOrder(orderSubmitVo);
            }else {
                orderSn= orderWebService.submitSeckillOrder(orderSubmitVo);
            }
            redirectAttributes.addAttribute("totalOrderSn", orderSn);
            return "redirect:" + orderHtml + "toPay.html";
        } catch (DuplicateFieldsException e) {
            log.error("错误信息:{}0", e.getMessage());
            log.error(LogUtils.getStackTraceInfo(e));
            return "redirect:" + orderHtml + "toTrade.html";
        }
    }


    @ResponseBody
    @GetMapping("send/message")
    public R sendMessage(@RequestParam("orderSn") String orderSn) {
        OrderBackVo payVo = new OrderBackVo();
        payVo.setOrderSn(orderSn);
        payVo.setMemberId(8L);
        payVo.setHasStock(0);
        String s = JSON.toJSONString(payVo);

        LocalMqEntity localMqEntity = new LocalMqEntity();
        localMqEntity.setBody(s);
        localMqEntity.setClassType("com.didi.gulimall.common.to.OrderBackVo");
        localMqEntity.setExchange("order-event-exchange");
        localMqEntity.setRouteKey("order.rollback.order");
        localMqEntity.setId(UUID.randomUUID().toString());

        rabbitTemplate.sendConvertAndSend(localMqEntity);
        return R.ok().put("msg", "发送成功");
    }

    @ResponseBody
    @GetMapping("send/message/fill")
    public R sendMessageFill(@RequestParam("orderSn") String orderSn) {
        OrderBackVo payVo = new OrderBackVo();
        payVo.setOrderSn(orderSn);
        payVo.setMemberId(8L);
        payVo.setHasStock(0);
        OrderItemVo orderItemVo = new OrderItemVo();
        orderItemVo.setSkuId(10L);
        List<OrderItemVo> itemVos = new ArrayList<>();
        itemVos.add(orderItemVo);
        payVo.setOrderItemVos(itemVos);
        LocalMqEntity localMqEntity = new LocalMqEntity();
        localMqEntity.setBody(JSON.toJSONString(payVo));
        localMqEntity.setExchange("order-event-exchange");
        localMqEntity.setRouteKey("order.release.#");
        localMqEntity.setClassType("com.didi.gulimall.common.to.OrderBackVo");
        localMqEntity.setId(UUID.randomUUID().toString());
        rabbitTemplate.sendConvertAndSend(localMqEntity);
        return R.ok().put("msg", "发送成功");
    }
}